<template>
    <div>
        <div style="margin-top: 10px;">
            <FormTitle>基础信息</FormTitle>
            <el-descriptions class="fixed-width-descriptions" title="" :column="4" border>
                <el-descriptions-item label="单据编号" label-align="left" align="left"
                    :class-name="!userInfo.orderNo ? 'my-content' : ''">
                    <div>{{ userInfo.orderNo ? '' : '创建后自动生成' }}</div>
                </el-descriptions-item>
                <el-descriptions-item label="制单人员" label-align="left" align="left" :class-name="'my-content'">
                    <div>{{ userInfo.userName }}</div>
                </el-descriptions-item>
                <el-descriptions-item label="制单时间" label-align="left" align="left" :class-name="'my-content'">
                    <div>{{ userInfo.time }}</div>
                </el-descriptions-item>
                <el-descriptions-item label="单据状态" label-align="left" align="left" :class-name="'my-content'">
                    <div>创建后自动生成</div>
                </el-descriptions-item>
                <el-descriptions-item label="结算状态" label-align="left" align="left" :class-name="'my-content'">
                    <div>创建后自动生成</div>
                </el-descriptions-item>
                <el-descriptions-item label="备注" label-align="left" align="left">
                     <div class="inputBorderNone">
                        <input v-model="ruleForm.remark" placeholder="请输入备注"  style="--el-input-border-color: transparent;"></input>
                    </div>
                </el-descriptions-item>
            </el-descriptions>

        </div>
        <div style="margin-top: 10px;">
            <FormTitle>药库信息</FormTitle>
            <el-descriptions class="fixed-width-descriptions" title="" :column="4" border>
                <el-descriptions-item label="入库药库" label-align="left" align="left">
                    <el-select v-model="ruleForm.storageId" placeholder="入库药库" filterable  style="width: 100%;">
                        <el-option v-for="item in storageData" :key="item.storageId" :label="item.storageName"
                            :value="item.storageId" />
                    </el-select>
                </el-descriptions-item>
                <el-descriptions-item label="供应商" label-align="left" align="left">
                    <el-select v-model="ruleForm.supplyId" filterable placeholder="供应商" @change="supplyChange"
                        style="width: 100%;">
                        <el-option v-for="item in supplyList" :key="item.supplyId" :label="item.supplyName"
                            :value="item.supplyId" />
                    </el-select>
                </el-descriptions-item>
                <el-descriptions-item label="联系人员" label-align="left" align="left" :class-name="'my-content'">
                    {{ storageInfo.managerName }}
                </el-descriptions-item>
                <el-descriptions-item label="联系电话" label-align="left" align="left" :class-name="'my-content'">
                    {{ storageInfo.managerPhone }}
                </el-descriptions-item>
            </el-descriptions>
        </div>
        <div style="margin-top: 10px;">
            <FormTitle>产品信息</FormTitle>
            <DrugProfileSelect style="margin-top: 10px;" :storageId="Number(dataType.storageId)"
                :columns="tableColumns" placeholder="搜索药品名或拼音缩写" :search-fields="['name', 'email']"
                @select="handleSelect"> </DrugProfileSelect>
            <el-table :data="ruleForm.detailList" border style="width: 100%;margin-top: 10px;" height="220px"
                :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }"
                header-cell-class-name="heardClassName">
                <el-table-column type="index" width="50" />
                <el-table-column property="drugName" label="药品名称" />
                <el-table-column property="guige" label="规格" />
                <el-table-column property="mfrName" label="生产厂家" />
                <el-table-column property="drugCategory" label="分类" />
                <el-table-column property="orderQty" label="采购数量" width="90">
                    <template #default="scope">
                        <el-input v-model="scope.row.orderQty" style="width:52px;"></el-input>
                    </template>
                </el-table-column>
                <el-table-column property="packUnitText" label="单位" width="80" />
                <el-table-column property="price" label="采购价" width="80" >
                    <template #default="scope">
                        <el-input v-model="scope.row.price" style="width:52px;"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="金额" width="80">
                    <template #default="scope">
                        {{ Number((scope.row.orderQty * scope.row.price).toFixed(2)) }}
                    </template>
                </el-table-column>
                <el-table-column property="batchNo" label="生产批号">
                    <template #default="scope">
                        <el-input v-model="scope.row.batchNo" style="width:100%;"></el-input>
                    </template>
                </el-table-column>
                <el-table-column property="batchDate" label="生产日期" width="190">
                    <template #default="scope">
                        <el-date-picker v-model="scope.row.batchDate" style="width:100%;" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                            type="date" placeholder="生产日期" />
                    </template>
                </el-table-column>
                <el-table-column property="expiryDate" label="有效日期" width="190">
                    <template #default="scope">
                        <el-date-picker v-model="scope.row.expiryDate" style="width:100%;" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                            type="date" placeholder="有效日期" />
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="操作" width="80">
                    <template #default="scope">
                        <el-button type="text" @click="detailListDel(scope.$index)" style="color:#D90000">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- <el-form-item prop="mfrId">
            <el-button type="primary" :disabled="upLoading" :loading="upLoading" style="margin-left: auto;margin-top: 20px;" @click="handleSubmit()">保存</el-button>
        </el-form-item> -->
    </div>
</template>

<script setup lang="ts">
import stores from '@/store';
import type {  PurchaseAdd } from '@/types/purchase'
import type { DrugInfo } from '@/types/drug'
import { addPurchase } from '@/api/purchase'
import type { List as storageList } from '@/types/storage/index';
import { getStorageList } from '@/api/storage'
import { getSupplyList } from '@/api/supply'
import type { SupplyInfo } from '@/types/supply';
import {getSupplierSelectList} from '@/api/account'
import {getStorageSelectList} from '@/api/medical'
const upLoading = ref(false)
//药库 
const storageData = ref<storageList[]>()
const getStorageLists = async () => {
    const res = await getStorageSelectList()
    if(res.code != '200'){
        //ElMessage.error(res.msg);
        return
    }
    storageData.value = res.data
}
getStorageLists()

//供应商
const storageInfo = ref<SupplyInfo>({
    managerPhone: '',
    managerName: ''
})

const supplyList = ref<SupplyInfo[]>([])
const getSupplyListData = async () => {
    let res = await getSupplierSelectList()
    if(res.code != '200'){
        //ElMessage.error(res.msg);
        return
    }
    supplyList.value = res.data
}
getSupplyListData()

//删除药品

const detailListDel = (index:number) =>{
ruleForm.value.detailList.splice(index,1)
}


const supplyChange = () => {
    for (let index = 0; index < supplyList.value.length; index++) {
        let item = supplyList.value[index];
        if (item?.supplyId == ruleForm.value.supplyId) {
            storageInfo.value.managerPhone = item?.managerPhone
            storageInfo.value.managerName = item?.managerName
        }
    }
}


//表单数据
 
const dataType = defineProps<{ dataType: Number, storageId: Number, }>();
const ruleForm = ref<PurchaseAdd>({
    remark: '',
    storageId: dataType.storageId,
    supplyId: '',
    detailList: [
    ],
})



//基本信息
const today = new Date()
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0');
const day = String(today.getDate()).padStart(2, '0');
const hours = String(today.getHours()).padStart(2, '0');
const minutes = String(today.getMinutes()).padStart(2, '0');
const seconds = String(today.getSeconds()).padStart(2, '0');

const userInfo = ref<any>(
    {
        userName: getUserInfo().empName,
        time: `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`,
    }
)



const iconStyle = computed(() => {
    const marginMap = {
        large: '8px',
        default: '6px',
        small: '4px',
    }
    return {
        marginRight: marginMap['large'] || marginMap.default,
    }
})



//选择药品
const UnitTypeEnum = ref<any>(stores.useBaseDataStore().getDictsSelect('UNIT'))
const DrugCategoryEnum = ref<any>(stores.useBaseDataStore().getEnumSelect('drugCategoryEnum'))
 


 
// 表格列配置
const tableColumns = [
    { prop: 'drugName', label: '药品', },
    { prop: 'guige', label: '规格', },
    { prop: 'mfrName', label: '厂家' },
    { prop: 'price', label: '单价', align: 'center' },
    { prop: 'stockQty', label: '库存', },
];

// 选中的数据
const selectedItem = ref<DrugInfo[]>();

// 处理选中事件  药品档案选择
const handleSelect = (item: DrugInfo) => {

    selectedItem.value?.push(item)
    ruleForm.value.detailList.push({
        drugId: item.drugId,
        orderQty: '',
        batchNo: '',
        price:'',
        batchDate: '',
        expiryDate: '',
        drugCategory: item.drugCategory,
        packUnitText:item.packUnitText,
        guige: item.guige,
        minPackQty: item.minPackQty,
        minPackUnit: item.minPackUnit,
        drugDosageUnit: item.drugDosageUnit,
        drugDosage: item.drugDosage,
        drugName: item.drugName,
        packUnit: item.packUnit,
        mfrName: item.mfrName
    })
};






const addProfileApi = async () => {
   
    let detailList = []

    for (let index = 0; index < ruleForm.value.detailList.length; index++) {
        let item = ruleForm.value.detailList[index];
        if(item){
            detailList.push({
                "drugId": item.drugId, //药品ID
                "orderQty": item.orderQty, //采购数量
                "price": Number((item.price * 100).toFixed(2)), //售价;100（分）
                "batchNo": item.batchNo, //生产批号
                "batchDate": item.batchDate, //生产日期
                "expiryDate": item.expiryDate //有效日期
            })
        }
    }
    let data = {
        remark: ruleForm.value.remark,
        storageId: ruleForm.value.storageId,
        supplyId: ruleForm.value.supplyId,
        detailList:detailList
    }
    let res = await addPurchase(data)
    upLoading.value = false
    if (res.code == '200') {
        ElMessage({
            type: 'success',
            message: res.msg
        });
        closeDrawer()

    } else {
        // ElMessage({
        //     type: 'warning',
        //     message: res.msg
        // });
    }

}

const updateProfileApi = async () => {
    // let res = await updateProfile(ruleForm.value)
    // if (res.code == '200') {
    //     ElMessage({
    //         type: 'success',
    //         message: res.msg
    //     });
    //     closeDrawer()

    // } else {
    //     ElMessage({
    //         type: 'warning',
    //         message: res.msg
    //     });
    // }
}

// , dataInfos: PurchaseAdd 


const ruleFormRef = ref();
defineExpose<{
  open: () => void;
}>({
  open() { 
    handleSubmit()
  },
});
const handleSubmit = async () => {
    upLoading.value = true
   if (dataType.dataType === 0) {
        addProfileApi();
    } else {
        updateProfileApi();
    }
};

// ruleForm.value = dataType.dataInfos


const emit = defineEmits(['closeDrawer']);
const closeDrawer = () => {
    emit('closeDrawer');
};
</script>
<style lang="scss">
.form1-ruleForm .el-form-item {
    display: block !important;
}

.my-content {
    background: var(--el-descriptions-item-bordered-label-background);
    ;
}

.fixed-width-descriptions .is-bordered-label {
    width: 90px;
}

.fixed-width-descriptions .is-bordered-content {
    width: 188px;
}
</style>